package com.wl2o2o.designpatterns.singleton;

/**
 * @Author <a href="https://github.com/wl2o2o">程序员CSGUIDER</a>
 * @From <a href="https://wl2o2o.github.io">CSGUIDER博客</a>
 * @CreateTime 2024/3/12
 */

public class NonThreadSafeSingleton {
    private static NonThreadSafeSingleton instance;

    private NonThreadSafeSingleton() {}

    // 注意：这里没有加锁，所以是线程不安全的
    public static NonThreadSafeSingleton getInstance() {
        if (instance == null) {
            // 在多线程环境下，两个线程可能同时发现 instance 为 null，并各自创建一个实例
            instance = new NonThreadSafeSingleton();
        }
        return instance;
    }

    @Override
    public String toString() {
        return "NonThreadSafeSingleton@" + Integer.toHexString(hashCode());
    }

    public static void main(String[] args) {
        // 创建两个并发线程来获取单例
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                System.out.println("Thread " + Thread.currentThread().getName() + ": " + NonThreadSafeSingleton.getInstance());
            }).start();
        }
    }
}
